package Algorithm.binaryTree;

//https://leetcode-cn.com/problems/binary-tree-tilt/
public class Leetcode563 {
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public int result = 0;

        public int findTilt(TreeNode root) {
            orderSearch(root);
            return result;
        }

        public int orderSearch(TreeNode root){
            if(root == null){
                return 0;
            }

            int leftSum = orderSearch(root.left);
            int rightSum = orderSearch(root.right);

            result += Math.abs(rightSum - leftSum);

            return leftSum + rightSum + root.val;
        }
    }
}
